﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Transactions;
using System.Configuration;
using System.IO;

namespace AllNations.UI
{
    public partial class PhotoManager : MakeItWeb.Framework.MakeItWebPage
    {
        public override bool IsPageAdministrator()
        {
            return IsInRole("Administrator") || IsInRole("PhotoAdmin");
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            btCreateAlbum.Click += new EventHandler(btCreateAlbum_Click);
            btAddPhotoToAlbum.Click += new EventHandler(btAddPhotoToAlbum_Click);
            btSavePhotoDetail.Click += new EventHandler(btSavePhotoDetail_Click);
            btSaveAlbumDetail.Click += new EventHandler(btSaveAlbumDetail_Click);
            if (!IsPostBack)
            {
                switch (Request.QueryString["View"])
                {
                    case "CreateAlbum":
                        ManagerViews.SelectedIndex = CreateAlbumView.Index;
                        break;
                    case "AddPhotoToAlbum":
                        ManagerViews.SelectedIndex = AddPhotoToAlbumView.Index;
                        break;
                    case "EditPhotoDetail":
                        ManagerViews.SelectedIndex = EditPhotoDetailView.Index;
                        MakeItWeb.Framework.Photo photo = MakeItWeb.Framework.Photo.GetPhoto(new Guid(Request.QueryString["PhotoId"]));
                        txtPhotoTitle.Text = photo.TitleTxt;
                        txtPhotoDesc.Text = photo.DescTxt;
                        imgSelectedPhoto.ImageUrl = string.Format("~/PhotoHandler.ashx?PhotoId={0}", photo.PhotoId);
                        break;
                    case "AlbumProperties":
                        ManagerViews.SelectedIndex = AlbumPropertiesView.Index;
                        MakeItWeb.Framework.Photoalbum album = MakeItWeb.Framework.Photoalbum.GetPhotoalbum(new Guid(Request.QueryString["PhotoalbumId"]));
                        txtAlbumTitleUpd.Text = album.TitleTxt;
                        txtAlbumDescUpd.Text = album.DescTxt;
                        break;
                }
            }
        }

        void btSaveAlbumDetail_Click(object sender, EventArgs e)
        {
            MakeItWeb.Framework.Photoalbum album = MakeItWeb.Framework.Photoalbum.GetPhotoalbum(new Guid(Request.QueryString["PhotoalbumId"]));
            album.TitleTxt = txtAlbumTitleUpd.Text.Trim();
            album.DescTxt = txtAlbumDescUpd.Text.Trim();
            album.ArchiveInd = cbArchiveInd.Checked;
            album.Save();

            if (album.ArchiveInd)
                ClientScript.RegisterStartupScript(GetType(), "OnLoad", "RefreshParentPage(true);", true);
            else
                ClientScript.RegisterStartupScript(GetType(), "OnLoad", "RefreshParentPage();", true);
        }

        void btSavePhotoDetail_Click(object sender, EventArgs e)
        {
            MakeItWeb.Framework.Photo photo = MakeItWeb.Framework.Photo.GetPhoto(new Guid(Request.QueryString["PhotoId"]));
            photo.TitleTxt = txtPhotoTitle.Text.Trim();
            photo.DescTxt = txtPhotoDesc.Text.Trim();
            photo.Save();

            ClientScript.RegisterStartupScript(GetType(), "OnLoad", "RefreshParentPage();", true);
        }

        void btAddPhotoToAlbum_Click(object sender, EventArgs e)
        {
            using (TransactionScope scope = new TransactionScope())
            {
                MakeItWeb.Framework.Photoalbum album = MakeItWeb.Framework.Photoalbum.GetPhotoalbum(new Guid(Request.QueryString["PhotoalbumId"]));

                Guid guidLastPhotoId = Guid.Empty;
                foreach (Telerik.Web.UI.UploadedFile file in raduploadAlbumPhotoAdd.UploadedFiles)
                {
                    try
                    {
                        guidLastPhotoId = SavePhoto(album, file);
                    }
                    catch (Exception)
                    {
                    }
                }
                if (guidLastPhotoId != Guid.Empty)
                {
                    album.LatestPhotoId = guidLastPhotoId;
                    album.Save();
                }

                scope.Complete();
            }
            ClientScript.RegisterStartupScript(GetType(), "OnLoad", "RefreshParentPage();", true);
        }

        private static Guid SavePhoto(MakeItWeb.Framework.Photoalbum album, Telerik.Web.UI.UploadedFile file)
        {
            // create photoalbum file directory
            string sRoot = string.Format(@"{0}\{1}", HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["PhotoRoot"]), album.PhotoalbumId);
            if (!System.IO.Directory.Exists(sRoot))
                System.IO.Directory.CreateDirectory(sRoot);

            string sFileName = file.FileName.Substring(file.FileName.LastIndexOf(@"\") + 1);
            string sImgFilename = string.Format(@"{0}\{1}", sRoot, sFileName);
            file.SaveAs(sImgFilename);    // save the file in the file system
            MakeItWeb.Framework.Photo photo = new MakeItWeb.Framework.Photo();
            photo.PhotoId = Guid.NewGuid();
            photo.PhotoalbumId = album.PhotoalbumId;
            photo.FilenameTxt = sFileName;
            photo.FilepathTxt = sImgFilename;
            string sTitle = formatFilenameForTitle(sFileName);
            photo.TitleTxt = sTitle;
            FileInfo fInfo = new FileInfo(sImgFilename);
            photo.DescTxt = string.Format("{0} {1}", sTitle, fInfo.CreationTime.ToShortDateString());
            photo.FilesizeNum = file.ContentLength;
            photo.Save();

            return photo.PhotoId;
        }

        private static string formatFilenameForTitle(string sFileName)
        {
            return sFileName.Replace("-", " ").Replace("_", " ");
        }

        void btCreateAlbum_Click(object sender, EventArgs e)
        {
            using (TransactionScope scope = new TransactionScope())
            {
                // save photo album information
                MakeItWeb.Framework.Photoalbum album = new MakeItWeb.Framework.Photoalbum();
                album.HtmlPageId = new Guid(Request.QueryString["HtmlPageId"]);
                album.PhotoalbumId = Guid.NewGuid();
                album.TitleTxt = txtAlbumTitle.Text.Trim();
                album.DescTxt = txtAlbumDesc.Text.Trim();
                album.Save();

                // create photoalbum file directory
                string sRoot = string.Format(@"{0}\{1}", Server.MapPath(ConfigurationManager.AppSettings["PhotoRoot"]), album.PhotoalbumId);
                if (!System.IO.Directory.Exists(sRoot))
                    System.IO.Directory.CreateDirectory(sRoot);

                Guid guidLastPhotoId = Guid.Empty;
                foreach (Telerik.Web.UI.UploadedFile file in raduploadAlbumPhoto.UploadedFiles)
                {
                    try
                    {
                        guidLastPhotoId = SavePhoto(album, file);
                    }
                    catch (Exception)
                    {
                    }
                }
                if (guidLastPhotoId != Guid.Empty)
                {
                    album.LatestPhotoId = guidLastPhotoId;
                    album.TitleTxt = txtAlbumTitle.Text.Trim();
                    album.DescTxt = txtAlbumDesc.Text.Trim();
                    album.Save();
                }

                scope.Complete();
            }
            ClientScript.RegisterStartupScript(GetType(), "OnLoad", "RefreshParentPage();", true);
        }
    }
}